package com.ikun.kunpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ikun.kunpicturebackend.annotation.AuthCheck;
import com.ikun.kunpicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ikun.kunpicturebackend.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.ikun.kunpicturebackend.api.aliyunai.sub.AliYunAiApi;
import com.ikun.kunpicturebackend.common.BaseResponse;
import com.ikun.kunpicturebackend.common.DeleteRequest;
import com.ikun.kunpicturebackend.common.ResultUtils;
import com.ikun.kunpicturebackend.domain.Picture;
import com.ikun.kunpicturebackend.domain.Space;
import com.ikun.kunpicturebackend.domain.User;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import com.ikun.kunpicturebackend.manager.auth.SpaceUserAuthManager;
import com.ikun.kunpicturebackend.manager.auth.StpKit;
import com.ikun.kunpicturebackend.manager.auth.annotation.SaSpaceCheckPermission;
import com.ikun.kunpicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.ikun.kunpicturebackend.model.dto.picture.*;
import com.ikun.kunpicturebackend.model.enums.PictureReviewStatusEnum;
import com.ikun.kunpicturebackend.model.vo.PictureTagCategory;
import com.ikun.kunpicturebackend.model.vo.PictureVO;
import com.ikun.kunpicturebackend.service.PictureService;
import com.ikun.kunpicturebackend.service.SpaceService;
import com.ikun.kunpicturebackend.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceService spaceService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    //本地缓存
    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024)
            .maximumSize(10000L)
            .expireAfterWrite(5L, TimeUnit.MINUTES)
            .build();

    /**
     * 上传图片或修改图片信息(重新上传)
     * @param multipartFile
     * @param uploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                   PictureUploadRequest uploadRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(multipartFile == null || uploadRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, uploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest,
                                               HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0,
                ErrorCode.PARAMS_ERROR);

        // 待删图片id
        Long id = deleteRequest.getId();
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        // 调service
        pictureService.deletePicture(id, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片【管理员】
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest updateRequest, HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(updateRequest == null || updateRequest.getId() <= 0,
                ErrorCode.PARAMS_ERROR);

        // 将请求转为实体类Picture
        Picture picture = new Picture();
        BeanUtil.copyProperties(updateRequest, picture);
        // 手动将tags转为JSON
        picture.setTags(JSONUtil.toJsonStr(updateRequest.getTags()));

        // 图片校验
        pictureService.validPicture(picture);

        // 查询图片是否存在
        Long id = updateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 空间校验
        Long spaceId = oldPicture.getSpaceId();
        if (spaceId != null) {
            ThrowUtils.throwIf(!oldPicture.getUserId().equals(loginUser.getId()), ErrorCode.OPERATION_ERROR);
        }
        // 补充审核参数
        pictureService.fillReviewParams(picture, loginUser);
        // 操作数据库更新图片信息
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取图片信息【管理员】
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");

        return ResultUtils.success(picture);
    }

    /**
     * 获取图片VO
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0 || request == null, ErrorCode.PARAMS_ERROR);
        // 获取图片信息
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        // 校验空间
        Space space = null;
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 获取权限列表
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表【管理员】
     * @param queryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest queryRequest) {
        ThrowUtils.throwIf(queryRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取当前页码和每页大小
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        // 分页查询数据库，构造QueryWrapper
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(queryRequest);
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize), queryWrapper);
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表VO
     *
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest queryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(queryRequest == null || request == null, ErrorCode.PARAMS_ERROR);
        // 获取当前页码和每页大小
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        // 对pageSize大小做限制
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);

        // 空间权限校验
        Long spaceId = queryRequest.getSpaceId();
        if (spaceId == null) {
            // 查公共图库
            // 只查看已过审的图片
            queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            queryRequest.setNullSpaceId(true);
        } else {
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            // 查私有空间的图片
            /*Space space = spaceService.getById(spaceId);
            User loginUser = userService.getLoginUser(request);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            queryRequest.setNullSpaceId(false);*/
        }

        // 分页查询数据库，构造QueryWrapper
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(queryRequest);
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize), queryWrapper);
        ThrowUtils.throwIf(picturePage == null, ErrorCode.NOT_FOUND_ERROR);
        // 转换
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 从缓存获取图片列表VO分页
     *
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest queryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(queryRequest == null || request == null, ErrorCode.PARAMS_ERROR);
        // 获取当前页码和每页大小
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        // 对pageSize大小做限制
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        // 只查看已过审的图片
        queryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 将请求参数转JSON获取字节数组，md5加密得到十六进制字符串
        String asHex = DigestUtils.md5DigestAsHex(JSONUtil.toJsonStr(queryRequest).getBytes(StandardCharsets.UTF_8));
        // 缓存key
        String localKey = "listPictureVOByPageWithCache:" + asHex;
        String redisKey = "kunpicture:listPictureVOByPageWithCache:" + asHex;

        // 查询缓存
        // 先查询本地缓存
        String localCache = LOCAL_CACHE.getIfPresent(localKey);
        if (StrUtil.isNotBlank(localCache)) {
            // 缓存命中，直接返回
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(localCache, Page.class);
            return ResultUtils.success(pictureVOPage);
        }
        // 再查询redis缓存
        String value = stringRedisTemplate.opsForValue().get(redisKey);
        // 缓存命中，直接返回,将缓存写入本地缓存
        if (StrUtil.isNotBlank(value)) {
            LOCAL_CACHE.put(localKey, value);
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(value, Page.class);
            return ResultUtils.success(pictureVOPage);
        }

        // 缓存都未命中
        // 分页查询数据库，构造QueryWrapper
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(queryRequest);
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize), queryWrapper);
        ThrowUtils.throwIf(picturePage == null, ErrorCode.NOT_FOUND_ERROR);
        // 转换
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 存入redis和本地缓存
        String pictureVOJson = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(localKey, pictureVOJson);
        // 设置过期时间：5-10分钟，防止缓存雪崩
        int time = 300 + RandomUtil.randomInt(0, 301);
        stringRedisTemplate.opsForValue().set(redisKey, pictureVOJson, time, TimeUnit.SECONDS);
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片
     * @param editRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest editRequest, HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(editRequest == null || editRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);

        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);

        pictureService.editPicture(editRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 获取标签和分类
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 图片审核【管理员】
     * @param pictureReviewRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 管理员批量导入图片
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    /**
     * 通过颜色搜索图片
     * @param colorRequest
     * @param request
     * @return
     */
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest colorRequest,
                                                              HttpServletRequest request) {
        ThrowUtils.throwIf(colorRequest == null || request == null, ErrorCode.PARAMS_ERROR);
        String picColor = colorRequest.getPicColor();
        Long spaceId = colorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> voList = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(voList);
    }

    /**
     * 批量修改图片的标签和分类
     * @param pictureEditByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建AI扩图任务
     * @param outPaintingTaskRequest
     * @param request
     * @return
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest outPaintingTaskRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(outPaintingTaskRequest == null || outPaintingTaskRequest.getPictureId() == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(outPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    @GetMapping("out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getOutPaintingTaskResponse(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse outPaintingTask = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(outPaintingTask);
    }
}
